import { defineStore } from 'pinia'
import { ref } from 'vue'
import { logout } from '@/api/auth'
import { getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const roleCode = ref(localStorage.getItem('userRole') || '')

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    roleCode.value = info.roleCode || ''
    localStorage.setItem('userInfo', JSON.stringify(info))
    localStorage.setItem('userRole', info.roleCode || '')
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    roleCode.value = ''
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userRole')
  }

  // 获取用户信息（仅在登录时调用）
  const loadUserInfo = async () => {
    try {
      const { data } = await getUserInfo()
      setUserInfo(data)
      return data
    } catch (error) {
      console.error('Failed to load user info:', error)
      return null
    }
  }

  // 退出登录
  const logoutAction = async () => {
    try {
      await logout()
      clearToken()
      clearUserInfo()
    } catch (error) {
      console.error('Logout failed:', error)
      // 即使退出接口调用失败，也要清除本地数据
      clearToken()
      clearUserInfo()
    }
  }

  // 获取用户角色
  const getRole = () => {
    // 从roleCode状态获取，这个状态在setUserInfo时会被正确设置
    return roleCode.value
  }

  return {
    token,
    userInfo,
    roleCode,
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    logoutAction,
    getRole,
    loadUserInfo
  }
}) 